package com.stylefeng.guns.rest.modular.wz.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.rest.common.base.controller.ApiBaseController;
import com.stylefeng.guns.rest.common.constant.Consts;
import com.stylefeng.guns.rest.common.constant.WzConsts;
import com.stylefeng.guns.rest.common.persistence.dao.*;
import com.stylefeng.guns.rest.common.persistence.model.*;
import com.stylefeng.guns.rest.common.util.StringUtils;
import com.stylefeng.guns.rest.common.util.WeinXinUtil;
import com.stylefeng.guns.rest.config.properties.JwtProperties;
import com.stylefeng.guns.rest.domain.Res;
import com.stylefeng.guns.rest.enums.*;
import com.stylefeng.guns.rest.modular.auth.util.JwtTokenUtil;
import com.stylefeng.guns.rest.modular.wz.api.v3.service.IWzAdvMapService;
import com.stylefeng.guns.rest.modular.wz.api.v3.service.IWzMapActivityService;
import com.stylefeng.guns.rest.modular.wz.cache.CacheService;
import com.stylefeng.guns.rest.modular.wz.service.IWzCouponService;
import com.stylefeng.guns.rest.modular.wz.service.IWzUserCouponService;
import com.stylefeng.guns.rest.modular.wz.service.impl.WzAdvServiceImpl;
import com.stylefeng.guns.rest.modular.wz.service.impl.WzMapRebateServiceImpl;
import com.stylefeng.guns.rest.modular.wz.service.impl.WzUserServiceImpl;
import com.stylefeng.guns.rest.modular.wz.util.weixin.AdvancedUtil;
import com.stylefeng.guns.rest.modular.wz.util.weixin.SNSUserInfo;
import com.stylefeng.guns.rest.modular.wz.util.weixin.Sign;
import com.stylefeng.guns.rest.modular.wz.util.weixin.WeixinOauth2Token;
import com.stylefeng.guns.rest.modular.wz.util.wz.DateUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.logging.Logger;

/**
 * 用户表
 */
@RestController
@RequestMapping("/wz/wzShare/")
public class WzShareApi extends ApiBaseController {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private WzUserMapper userMapper;
    @Autowired
    private WzPrizeMapper prizeMapper;
    @Autowired
    private WzPrizeWinnersMapper prizeWinnersMapper;
    @Autowired
    private WzUserFinanceRecordMapper userFinanceRecordMapper;
    @Autowired
    private WzUserCouponMapper userCouponMapper;
    @Autowired
    private WzUserServiceImpl userService;
    @Autowired
    private WzCouponMapper couponMapper;
    @Autowired
    private WzUserInfoMapper userInfoMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private AsyncService asyncService;
    @Autowired
    private WzConsts wzConsts;
    @Autowired
    private WzUserFixedInfoMapper userFixedInfoMapper;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private WzShareMapper shareMapper;
    @Autowired
    private WzAdvShareMapper advShareMapper;
    @Autowired
    private WzUserAdvRecordMapper userAdvRecordMapper;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private WzAdvMapper advMapper;
    @Autowired
    private WzRedpacketMapper redpacketMapper;
    @Autowired
    private WzAdvServiceImpl advService;
    @Autowired
    private WzAdvMapCategoryMapper advMapCategoryMapper;
    @Autowired
    private IWzMapActivityService mapActivityService;
    @Autowired
    private IWzAdvMapService advMapService;
    @Autowired
    private IWzUserCouponService userCouponService;
    @Autowired
    private IWzCouponService couponService;
    @Autowired
    private WzUserActivityMapper userActivityMapper;
    @Autowired
    private WzMapMergeMapper mapMergeMapper;
    @Autowired
    private WzMapRebateMapper mapRebateMapper;
    @Autowired
    private WzUserRebateMapper userRebateMapper;
    @Autowired
    private WzRebateShareMapper rebateShareMapper;
    @Autowired
    private WzFinanceService financeService;
    @Autowired
    private WzUserOauthMapper userOauthMapper;
    @Autowired
    private WzMapRebateServiceImpl mapRebateService;

    private static final String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID1&secret=SECRET1";
    private static final String ticketUrl = "http://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=ACCESS_TOKEN1";
    public static String accessToken = "";
    public static String jsapiTicket = "";
    public static Long start = 0L;

    //首页图片数据
    @RequestMapping("indexPics")
    public Object indexPics(){
        Map<String,Object> data=new HashMap();
        List<String> longPic=new ArrayList();
        List<String> shortPic=new ArrayList();
        //活动中心图片
        List<Map<String,Object>> activityPics = cacheService.wzSysFile(EnWzSysFile.Type_Index_Activity_Pics.getIndex());
        for(Map activityPic:activityPics){
            longPic.add(activityPic.get("fileUrl").toString());
        }
        //中部图片
        List<Map<String,Object>> middlePics = cacheService.wzSysFile(EnWzSysFile.Type_Index_Middle_Pics.getIndex());
        for(Map middlePic:middlePics){
            shortPic.add(middlePic.get("fileUrl").toString());
        }
        int size=longPic.size()+shortPic.size();
        data.put("longPic",longPic);
        data.put("shortPic",shortPic);
        data.put("size",size);
        return data;
    }


    //分享返利
    @RequestMapping("mapRebate")
    public void mapRebate(HttpServletResponse response, String mapRebateId, String userCode, String userRebateId,String adCode) throws Exception {
        if (Consts.dev.equals("true")) {
            response.sendRedirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + Consts.appid + "&redirect_uri=http%3a%2f%2f50wz.viphk.ngrok.org%2fwz%2fwzShare%2fmapRebate%2findex%3fmapRebateId%3d" + mapRebateId + "%26userCode%3d" + userCode + "%26userRebateId%3d" + userRebateId + "%26adCode%3d" + adCode +"%26isDev%3d1&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
        } else {
            response.sendRedirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + Consts.appid + "&redirect_uri=http%3a%2f%2fwzapp.50waizhuan.com%2fwz%2fwzShare%2fmapRebate%2findex%3fmapRebateId%3d" + mapRebateId + "%26userCode%3d" + userCode + "%26userRebateId%3d" + userRebateId + "%26adCode%3d" + adCode +"%26isDev%3d0&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
        }
    }

    @RequestMapping("mapRebate/index")
    public void mapRebateIndex(HttpServletResponse response, HttpServletRequest request, String mapRebateId, String userCode, String userRebateId,String adCode,String isDev) throws Exception {
        WzMapRebate mapRebate = mapRebateMapper.selectById(mapRebateId);
        if (mapRebate != null) {
            String code = request.getParameter("code");
            String shareTitle="帮我点击下，我正在参加"+mapRebate.getMerchantName()+"的返利活动";
            String shareImg=mapRebate.getPic();
            response.sendRedirect(mapRebate.getShareLink() + "?mapRebateId=" + mapRebateId + "&userCode=" + userCode + "&userRebateId=" + userRebateId + "&code=" + code +"&adCode="+ adCode+"&shareTitle="+getURLEncoderString(shareTitle)+"&shareImg="+getURLEncoderString(shareImg)+"&isMapRebate=1&isDev="+isDev);
        } else {
            response.sendRedirect("http://www.50waizhuan.com/download");
        }
    }

    public static String getURLEncoderString(String str) {
        String result = "";
        if (null == str) {
            return "";
        }
        try {
            result = java.net.URLEncoder.encode(str, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }


    @RequestMapping("mapRebate/main")
    public void mapRebateMain(WzUserRebate wzUserRebate, String code){
        Long userRebateId=wzUserRebate.getUserRebateId();
        WzUserRebate userRebate=userRebateMapper.selectById(userRebateId);
        if (userRebate.getEndTime().before(new Date())) {
            if(userRebate.getStatus() != EnWzMapRebate.USERREBATE_STATUS_EXPIRED.getIndex()){
                userRebate.setStatus(EnWzMapRebate.USERREBATE_STATUS_EXPIRED.getIndex());
                userRebateMapper.updateById(userRebate);
            }
            return;
        }else{
            if(userRebate.getStatus() == EnWzMapRebate.USERREBATE_STATUS_GOING.getIndex()){//活动进行中
                WeixinOauth2Token weixinOauth2Token = AdvancedUtil.getOauth2AccessToken(Consts.appid, Consts.appSecret, code);
                String openid = weixinOauth2Token.getOpenId();
                String accessToken = weixinOauth2Token.getAccessToken();
                SNSUserInfo snsUserInfo = AdvancedUtil.getSNSUserInfo(accessToken, openid);
                WzUserOauth userOauth = cacheService.userOauth(wzUserRebate.getUserCode());
                if(userOauth != null){
                    if(!userOauth.getUnionid().equals(snsUserInfo.getUnionid().toString())) {
                        //是否点击过当前返利活动
                        int rebateShareNumber = rebateShareMapper.selectCount(new EntityWrapper<WzRebateShare>().eq("user_rebate_id", userRebateId).eq("openid", openid));
                        if (rebateShareNumber > 0) {
                            return;
                        } else {
                            userRebate.setShareNumber(userRebate.getShareNumber() + 1);
                            WzRebateShare rebateShare = new WzRebateShare();
                            rebateShare.setMapRebateId(userRebate.getMapRebateId());
                            rebateShare.setUserRebateId(userRebateId);
                            rebateShare.setOpenid(openid);
                            rebateShare.setGender(snsUserInfo.getSex());
                            rebateShare.setUnionid(snsUserInfo.getUnionid());
                            rebateShare.setNickName(snsUserInfo.getNickname());
                            rebateShare.setAvatarUrl(snsUserInfo.getHeadImgUrl());
                            rebateShare.setCreateTime(new Date());
                            if (userRebate.getShareNumber() >= userRebate.getNeedShareNumber()) {//人数已满
                                userRebate.setShareNumber(userRebate.getNeedShareNumber());
                                userRebate.setStatus(EnWzMapRebate.USERREBATE_STATUS_END.getIndex());
                                boolean r = financeService.userRebateEnd(rebateShare, userRebate);
                            }else{//人数未满
                                boolean r = mapRebateService.rebateShareSave(rebateShare, userRebate);
                            }
                        }
                    }
                }else{//自己发起的返利不能点击
                    return;
                }
            }
        }
    }

    //拼单数据
    @RequestMapping("mapMergeData")
    public Object mapMergeData(Long advMapId){
        String sql="pic,merchant_name As merchantName,benefit,merge_price As price,sales";
        return mapMergeMapper.selectMaps(new EntityWrapper<WzMapMerge>().setSqlSelect(sql).eq("adv_map_id",advMapId).eq("status", EnWzMapMerge.STATUS_RELEASE.getIndex()));
    }

    //返利数据
    @RequestMapping("mapRebateData")
    public Object mapRebateData(Long advMapId){
        String sql="pic,merchant_name As merchantName,benefit,rebate_price As price,sales";
        return mapRebateMapper.selectMaps(new EntityWrapper<WzMapRebate>().setSqlSelect(sql).eq("adv_map_id",advMapId).eq("status", EnWzMapRebate.STATUS_RELEASE.getIndex()));
    }


    //网页端扫描二维码接口
    @RequestMapping("scanQRcode")
    public void scanQRcode(Integer type,String advMapId,HttpServletResponse response) throws IOException {
        if(type == 1){
            WzAdvMap wzadvMap = advMapService.selectById(advMapId);
            int isDev;
            if (Consts.dev.equals("true")) {
                isDev=1;
            }else{
                isDev=0;
            }
            response.sendRedirect(wzadvMap.getShareLink()+"?advMapId="+advMapId+"&showMapMerge=1&isDev="+isDev);

        }else{
            response.sendRedirect("http://www.50waizhuan.com/download");
        }
    }

    //扫描二维码页面调用接口
    @RequestMapping("scanQRcodeData")
    public List scanQRcodeData(String advMapId){
        List<WzMapActivity> activityData = mapActivityService.selectList(new EntityWrapper<WzMapActivity>().eq("adv_map_id", advMapId).eq("status", EnWzMapActivity.STATUS_RELEASE.getIndex()).ge("end_time", new Date()));
        return activityData;
    }


    @RequestMapping("mapActivityBenefit")
    public String advMapCategory(String advMapId) {
        StringBuilder sb = new StringBuilder();
        //活动数据
        List<Object> activityData = mapActivityService.selectObjs(new EntityWrapper<WzMapActivity>().setSqlSelect("benefit").eq("adv_map_id", advMapId).eq("status", EnWzMapActivity.STATUS_RELEASE.getIndex()).ge("end_time", new Date()));
        for (Object benefit : activityData) {
            sb.append(benefit + "，");
        }
        int length=sb.toString().length();
        if (length > 0) {
            if(length<=23){
                return sb.toString();
            }else if(length<=40){
                return sb.toString().substring(0,23)+"<br/>"+sb.toString().substring(23);
            }else{
                return sb.toString().substring(0,23)+"<br/>"+sb.toString().substring(23,40)+"...";
            }
        } else {
            return "0";
        }
    }


    //分享出去的地图活动
    @RequestMapping("mapActivity")
    public void mapActivity(HttpServletResponse response, String advMapId, String userCode, String mapActivityId,String adCode) throws Exception {
        if (Consts.dev.equals("true")) {
            response.sendRedirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + Consts.appid + "&redirect_uri=http%3a%2f%2f50wz.viphk.ngrok.org%2fwz%2fwzShare%2fmapActivity%2findex%3fadvMapId%3d" + advMapId + "%26userCode%3d" + userCode + "%26mapActivityId%3d" + mapActivityId  + "%26adCode%3d" + adCode+ "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
        } else {
            Map<String,Object> commomSys = cacheService.commomSys("commomSys");
            if(commomSys.get("ios_version").toString().equals("1.5.0")){
                response.sendRedirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + Consts.appid + "&redirect_uri=http%3a%2f%2fwzapp.50waizhuan.com%2fwz%2fwzShare%2fmapActivity%2findex%3fadvMapId%3d" + advMapId + "%26userCode%3d" + userCode + "%26mapActivityId%3d" + mapActivityId  + "%26adCode%3d" + adCode+ "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
            }else{
                response.sendRedirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + Consts.appid + "&redirect_uri=http%3a%2f%2f50wz.viphk.ngrok.org%2fwz%2fwzShare%2fmapActivity%2findex%3fadvMapId%3d" + advMapId + "%26userCode%3d" + userCode + "%26mapActivityId%3d" + mapActivityId  + "%26adCode%3d" + adCode+ "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
            }
        }
    }


    @RequestMapping("mapActivity/main")
    public void mapActivityMain(WzMapActivity activity, String code) throws Exception {
        Long mapActivityId = activity.getMapActivityId();
        Long userCode = activity.getUserCode();
        Long advMapId = activity.getAdvMapId();
        WzAdvMap wzadvMap = advMapService.selectById(advMapId);
        if (wzadvMap != null) {
            WzUser wzUser = cacheService.user(userCode);
            WeixinOauth2Token weixinOauth2Token = AdvancedUtil.getOauth2AccessToken(Consts.appid, Consts.appSecret, code);
            List<WzUserActivity> userActivityList = userActivityMapper.selectList(new EntityWrapper<WzUserActivity>().eq("user_code", userCode).eq("map_activity_id", mapActivityId).eq("status", EnWzMapActivity.USER_ACTIVITY_Going.getIndex()));
            if (userActivityList.size() > 0) {
                WzUserActivity userActivity = userActivityList.get(0);
                //该活动已经到期
                if (userActivity.getEndTime().before(new Date())) {
                    userActivity.setStatus(EnWzMapActivity.USER_ACTIVITY_Expired.getIndex());
                    int r = userActivityMapper.updateById(userActivity);
                    return;
                } else {
                    String openid = weixinOauth2Token.getOpenId();
                    //活动id对应的userMapAvtivity
                    List<Map<String, Object>> userMapAvtivities = userActivityMapper.selectMaps(new EntityWrapper<WzUserActivity>().setSqlSelect("user_map_activity_id As userMapActivityId,usetype").eq("map_activity_id", mapActivityId));
                    for (Map userMapAvtivity : userMapAvtivities) {
                        if ("1".equals(userMapAvtivity.get("usetype").toString())) {//限每人每天可领一次
                            List<WzShare> shares = shareMapper.selectList(new EntityWrapper<WzShare>().eq("target_id", userMapAvtivity.get("userMapActivityId").toString()).eq("openid", openid).eq("DATE_FORMAT(create_time,'%Y-%m-%d')", DateUtil.toString(new Date())));
                            //今天是否点击过这个活动
                            if (shares.size() > 0) {
                                return;
                            }
                        } else {
                            List<WzShare> shares = shareMapper.selectList(new EntityWrapper<WzShare>().eq("target_id", userMapAvtivity.get("userMapActivityId").toString()).eq("openid", openid));
                            //是否点击过这个活动
                            if (shares.size() > 0) {
                                return;
                            }

                        }
                    }
                    List<WzShare> shares = shareMapper.selectList(new EntityWrapper<WzShare>().eq("target_id", userActivity.getUserMapActivityId()).eq("openid", openid));
                    if (shares.size() > 0) {//该用户已经参与当前用户分享点击
                        return;
                    } else {
                        String accessToken = weixinOauth2Token.getAccessToken();
                        SNSUserInfo snsUserInfo = AdvancedUtil.getSNSUserInfo(accessToken, openid);
                        snsUserInfo.getCity();
                        WzShare share = new WzShare();
                        share.setCreateTime(new Date());
                        share.setTargetId(userActivity.getUserMapActivityId());
                        share.setAvatarUrl(snsUserInfo.getHeadImgUrl());
                        share.setOpenid(snsUserInfo.getOpenId());
                        share.setType(EnWz.SHARE_Type_Activity.getIndex());
                        share.setGender(snsUserInfo.getSex());
                        share.setNickName(WeinXinUtil.emojiFilter(snsUserInfo.getNickname()));
                        share.setUserCode(userCode);
                        share.setUnionid(snsUserInfo.getUnionid());
                        //地图活动
                        WzMapActivity mapActivity = mapActivityService.selectById(userActivity.getMapActivityId());
                        int shareNum = mapActivity.getNeedShareNumber();
                        userActivity.setShareNumber(userActivity.getShareNumber() + 1);
                        if (userActivity.getShareNumber() == shareNum) {
                            userActivity.setStatus(EnWzMapActivity.USER_ACTIVITY_End.getIndex());
                            WzCoupon coupon = couponService.selectOne(new EntityWrapper<WzCoupon>().eq("coupon_id", mapActivity.getCouponId()));
                            if (coupon != null) {
                                WzUserCoupon userCoupon = new WzUserCoupon();
                                userCoupon.setUserCode(userCode);
                                userCoupon.setCouponId(coupon.getCouponId());
                                userCoupon.setUserMapActivityId(userActivity.getUserMapActivityId().toString());//我的活动id
                                userCoupon.setPic(mapActivity.getPic());
                                userCoupon.setAdvMapId(coupon.getAdvMapId().toString());
                                userCoupon.setRule(coupon.getRule());
                                userCoupon.setNickName(wzUser.getNickName());
                                userCoupon.setAvatarUrl(wzUser.getAvatarUrl());
                                userCoupon.setType(coupon.getType());
                                userCoupon.setSubtype(coupon.getSubtype());
                                userCoupon.setStatus(EnWzUser.COUPON_STATUS_NORMAL.getIndex());
                                userCoupon.setBeginTime(coupon.getBeginTime());
                                userCoupon.setEndTime(coupon.getEndTime());
                                userCoupon.setCreateTime(new Date());
                                userCouponService.insert(userCoupon);
                                WzUserMessage userMessage = new WzUserMessage();//用户消息
                                userMessage.setCreateTime(new Date());
                                userMessage.setType(EnWzUser.Message_Type_AdvMap_Activity_Redpacket.getIndex());//跳转周边活动、红包统计页面
                                userMessage.setUserCode(userCode);
                                userMessage.setContent("尊敬的用户，您有一个地图活动已完成，请注意查看!");
                                userMessage.setTitle("一个活动已完成");
                                asyncService.checkUserAdv(userMessage, wzUser, userMessage.getType(), null);
                            }
                        }
                        int r = userActivityMapper.updateById(userActivity);
                        if (r > 0) {
                            shareMapper.insert(share);
                        }
                    }
                }
            } else {
                return;
            }

        }

    }

    @RequestMapping("mapActivity/index")
    public void mapActivityIndex(HttpServletResponse response, HttpServletRequest request, String advMapId, String userCode, String mapActivityId,String adCode) throws Exception {
            WzAdvMap wzadvMap = advMapService.selectById(advMapId);
        if (wzadvMap != null) {
            String code = request.getParameter("code");
            response.sendRedirect(wzadvMap.getShareLink() + "?advMapId=" + advMapId + "&userCode=" + userCode + "&mapActivityId=" + mapActivityId + "&code=" + code+"&adCode="+adCode+"&isMapActivity=1");
        } else {
            response.sendRedirect("http://www.50waizhuan.com/download");
        }
    }


    /**
     * 调用为微信接口
     */
    @RequestMapping("api")
    public Res api(HttpServletRequest request, String url) throws Exception {
        Map<String, String> map = setShareConfig(request, url);
        return Res.success(map);
    }

    public Map<String, String> setShareConfig(HttpServletRequest request, String url) throws Exception {
        //accessToken
        Long date = new Date().getTime();
        Long a = date - start;
        if (StringUtils.isBlankStr(accessToken) || a >= 3500000L) {
            accessToken = getAccessToken();
            jsapiTicket = getTicket(accessToken);
            start = date;
            System.out.println("-------accessToken 超时，重新获取--------" + accessToken);
        }
        if (StringUtils.isBlankStr(jsapiTicket)) {
            jsapiTicket = getTicket(accessToken);
            System.out.println("-------jsapiTicket 超时，重新获取--------" + jsapiTicket);
        }
        Map<String, String> ret = Sign.sign(jsapiTicket, url);
        request.setAttribute("url", ret.get("url"));
        request.setAttribute("jsapi_ticket", ret.get("jsapi_ticket"));
        request.setAttribute("nonceStr", ret.get("nonceStr"));
        request.setAttribute("timestamp", ret.get("timestamp"));
        request.setAttribute("signature", ret.get("signature"));
        request.setAttribute("appId", Consts.appid);
        return ret;
    }

    ;

    private static String getAccessToken() throws Exception {
        String accessToken = null;
        String url = accessTokenUrl.replace("APPID1", Consts.appid).replace("SECRET1",
                Consts.appSecret);
        String result = getURLContent(url);
        System.out.println(result);
        accessToken = result.split("access_token")[1].split("expires_in")[0]
                .replaceAll("\"", "").replaceAll(",", "").replaceAll(" ", "")
                .replaceAll(":", "");
        System.out.println("accessToken:" + accessToken);
        return accessToken;
    }

    private static String getTicket(String accessToken) throws Exception {
        String ticket = null;
        String url = ticketUrl.replace("ACCESS_TOKEN1", accessToken);
        String result = getURLContent(url);
        System.out.println(result);
        ticket = result.split("ticket")[1].split("expires_in")[0]
                .replaceAll("\"", "").replaceAll(",", "").replaceAll(" ", "")
                .replaceAll(":", "");
        System.out.println("ticket:" + ticket);
        return ticket;
    }

    public static String getURLContent(String url)
            throws MalformedURLException, IOException {
        String result = "";
        BufferedReader in = null;
        URL realUrl = new URL(url);
        // 打开和URL之间的连接
        URLConnection connection = realUrl.openConnection();
        // 设置通用的请求属性
        connection.setRequestProperty("accept", "*/*");
        connection.setRequestProperty("connection", "Keep-Alive");
        connection.setRequestProperty("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        // 建立实际的连接
        connection.connect();
        // 获取所有响应头字段
        Map<String, List<String>> map = connection.getHeaderFields();
        // 定义 BufferedReader输入流来读取URL的响应
        in = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
        // 使用finally块来关闭输入流
        if (in != null) {
            in.close();
        }
        return result;
    }

    @Transactional
    @RequestMapping("index")
    public void index(HttpServletResponse response, String advId, HttpServletRequest request, String userCode,String screenCity) throws Exception {
        String code = request.getParameter("code");
//        WeixinOauth2Token weixinOauth2Token = AdvancedUtil.getOauth2AccessToken(Consts.appid, Consts.appSecret, code);
//        String openid = weixinOauth2Token.getOpenId();
//        String accessToken = weixinOauth2Token.getAccessToken();
//        SNSUserInfo snsUserInfo = AdvancedUtil.getSNSUserInfo(accessToken, openid);

        if (StringUtils.isBlankStr(userCode) || userCode.equals("undefined")) {
            response.sendRedirect("http://share.50waizhuan.com/" + advId + ".html");
            return;
        }
        WzAdv adv = advMapper.selectById(Long.parseLong(advId));
        if (adv.getEndTime().before(new Date()) || StringUtils.isBlankStr(userCode) || userCode.equals("undefined")) {
                response.sendRedirect("" + Consts.Adv_Share_Domain + "/" + advId + ".html");
                return;
        }
        if(userCode.length() > 21) {
            userCode = getUsernameFromToken(userCode);
        }
        List<WzAdvShare> advShares = advShareMapper.selectList(new EntityWrapper<WzAdvShare>().eq("user_code", Long.parseLong(userCode)).eq("adv_id", Long.parseLong(advId)));
        WzAdvShare advShare = null;
        if (advShares.size() <= 0 && adv.getEndTime().after(new Date())) {
            //分享人数上限
            if (adv.getShareAverageReward() != 0) {
                int c = advShareMapper.selectCount(new EntityWrapper<WzAdvShare>().eq("adv_id", Long.parseLong(advId)).eq("share_reward", -1));
                int m = adv.getShareReward() / adv.getShareAverageReward();
                if (c >= m) {
                        response.sendRedirect("" + Consts.Adv_Share_Domain + "/" + advId + ".html");
                        return;
                }
            }
            advShare = new WzAdvShare();
            advShare.setCreateTime(new Date());
            advShare.setUserCode(Long.parseLong(userCode));
            advShare.setAdvId(adv.getAdvId());
            advShare.setShareNumber(0);
            advShare.setCoverUrl(adv.getCoverUrl());
            advShare.setStatus(adv.getStatus());
            advShare.setClickNumber(0);
            advShare.setSubtype(adv.getSubtype());
            WzUser user = cacheService.user(Long.parseLong(userCode));
            advShare.setNickName(user.getNickName());
            advShare.setAvatarUrl(user.getAvatarUrl());
            advShare.setMobileType(user.getMobileType());
            advShare.setShareReward(-1);
            int r = advShareMapper.insert(advShare);
        } else {
            advShare = advShares.get(0);
        }
        advShare.setClickNumber(advShare.getClickNumber() + 1);
        int r = advShareMapper.updateById(advShare);
        response.sendRedirect("" + Consts.Adv_Share_Domain + "/" + advId + ".html?advId="+advId+"&userCode=" + userCode+"&screenCity="+screenCity+"&code="+code);
    }

    @Transactional
    @RequestMapping("wzAdv/main")
    public void wzAdvMain(String advId, String code,String userCode){
        WeixinOauth2Token weixinOauth2Token = AdvancedUtil.getOauth2AccessToken(Consts.appid, Consts.appSecret, code);
        String openid = weixinOauth2Token.getOpenId();
        WzAdv adv = advMapper.selectById(Long.parseLong(advId));
        List<WzShare> shares = shareMapper.selectList(new EntityWrapper<WzShare>().eq("type",1).eq("target_id", Long.parseLong(advId)).eq("openid", openid));
        List<WzAdvShare> advShares = advShareMapper.selectList(new EntityWrapper<WzAdvShare>().eq("user_code", Long.parseLong(userCode)).eq("adv_id", Long.parseLong(advId)));
        if(advShares.size() > 0){
            WzAdvShare advShare=advShares.get(0);
            if (shares.size() > 0 || adv.getEndTime().before(new Date())) {

            } else {
                String accessToken = weixinOauth2Token.getAccessToken();
                SNSUserInfo snsUserInfo = AdvancedUtil.getSNSUserInfo(accessToken, openid);
                WzShare share = new WzShare();
                share.setCreateTime(new Date());
                share.setTargetId(adv.getAdvId());
                share.setAvatarUrl(snsUserInfo.getHeadImgUrl());
                share.setOpenid(snsUserInfo.getOpenId());
                share.setGender(snsUserInfo.getSex());
                share.setNickName(WeinXinUtil.emojiFilter(snsUserInfo.getNickname()));
                share.setUserCode(Long.parseLong(userCode));
                share.setUnionid(snsUserInfo.getUnionid());
                if (advShare.getShareReward() == 0) {
                    advShare.setShareReward(-1);
                }
                advShare.setShareNumber(advShare.getShareNumber() + 1);
                int r = advShareMapper.updateById(advShare);
                if (r > 0) {
                    shareMapper.insert(share);
                }
            }
        }
    }



    /**
     * 分享 snsapi_userinfo
     */
    @RequestMapping("share")
    public void share(HttpServletResponse response, String advId, Integer type, String userCode,String screenCity) throws Exception {
        if (Consts.dev.equals("true")) {
            response.sendRedirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + Consts.appid + "&redirect_uri=http%3a%2f%2f50wz.viphk.ngrok.org%2fwz%2fwzShare%2findex%3fadvId%3d" + advId + "%26type%3d" + type + "%26userCode%3d" + userCode + "%26screenCity%3d"+screenCity+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
        } else {
            response.sendRedirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + Consts.appid + "&redirect_uri=http%3a%2f%2fwzapp.50waizhuan.com%2fwz%2fwzShare%2findex%3fadvId%3d" + advId + "%26type%3d" + type + "%26userCode%3d" + userCode + "%26screenCity%3d"+screenCity+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
        }
    }

    /**
     * 获取用户名从token中
     */
    public String getUsernameFromToken(String token) {
        return getClaimFromToken(token).getSubject();
    }

    /**
     * 获取jwt的payload部分
     */
    public Claims getClaimFromToken(String token) {
        return Jwts.parser()
                .setSigningKey(jwtProperties.getSecret())
                .parseClaimsJws(token)
                .getBody();
    }


    @RequestMapping("MP_verify_o2FHVNJqv9FH0BYP.txt")
    public String test() {
        ModelAndView modelAndView = new ModelAndView("/static/MP_verify_o2FHVNJqv9FH0BYP");
        return "o2FHVNJqv9FH0BYP";
    }

}

